<template>
    <div class="compressImgContent">
        <div class="compressImgBefore">
            <van-uploader
                v-model="fileList"
                :after-read="afterRead"
                :max-count="1"
                :max-size="isOverSize"
                style="position: relative;"
            />
            <!-- reupload // 覆盖上传 -->
            <div class="imgInfo" v-if="fileList && fileList.length">
                <p>图片信息：</p>
                <p>类型为：<span>{{ typeBefore }}</span></p>
                <p>压缩前为：<span>{{ sizeBefore }}KB</span></p>
                <p>{{ `宽高为${sizeBeforeWidth} * ${sizeBeforeHeight}` }}</p>
            </div>
        </div>
        <div class="compressImgBtn">
            <van-button v-if="compressorAfter" style="width: 100%;border-radius: 16px;border: none; transition: all 0.3s ease;" :class="{ active: isActive }" type="warning" @click="clean">重新开始</van-button>
            <van-button v-else style="width: 100%;background: #15256a;color: #FFF;border-radius: 16px;border: none; transition: all 0.3s ease;"
                :class="{ active: isActive }"
                @click="onturn" :aria-disabled="compressorAfter">开始压缩</van-button>
        </div>
        <div class="compressImgAfter" v-if="compressorAfter">
            <div class="compressImgAfterImg">
                <!-- <img :src="compressorAfter" alt=""> -->
                <van-image
                    width="50%"
                    height="auto"
                    fit="contain"
                    :src="compressorAfter"
                />
            </div>
            <div class="imgInfo">
                <p>图片信息：</p>
                <p>类型为：<span>{{ typeAfter }}</span></p>
                <p>压缩后为：<span>{{ sizeAfter }}KB</span></p>
                <p>{{ `宽高为${sizeAfterWidth} * ${sizeAfterHeight}` }}</p>
            </div>
        </div>
        <div class="compressImgResult" v-if="compressorAfter">
            <p>对比之前压缩了：<span>{{ sizeValue }}KB</span></p>
        </div>
        <div class="compressImgBtn">
            <van-button v-if="compressorAfter" style="width: 100%;" type="danger" @click="download">点击下载压缩后的图片</van-button>
        </div>
    </div>
</template>
    
<script setup lang="ts">
import { ref, onMounted, computed, onUnmounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { showToast, showFailToast, showConfirmDialog } from 'vant'
import { getBase64, useCompressor } from '@/utils/plugins'
import useSettingStore from '@/store/modules/setting'
const settings = useSettingStore()

const route = useRoute()
const router = useRouter()

const isActive = ref<boolean>(false)
const fileList = ref<any>([

]);

const handleClick = () => {
    isActive.value = !isActive.value
    setTimeout(() => {
        isActive.value = !isActive.value
    }, 100)
}

const isOverSize = (file: any) => {
    console.log(file);
    console.log(file.type);
    if (file.type == 'image/jpeg' || file.type == 'image/png') {
        return false;
    } else {
        showToast('请选择格式为jpg或png类型的图片')
        return true;
    }
    // const maxSize = file.type == 'image/jpeg' ? 500 * 1024 : 1000 * 1024;
    // return file.size >= maxSize;
};

const sizeBefore = ref<string>('')
const sizeBeforeWidth = ref<string>('')
const sizeBeforeHeight = ref<string>('')
const typeBefore = ref<string>('')

const sizeAfter = ref<string>('')
const sizeAfterWidth = ref<string>('')
const sizeAfterHeight = ref<string>('')
const typeAfter = ref<string>('')

const compressorAfter = ref<string>('')


const sizeValue = computed(() => {
    const result = ((Number(sizeBefore.value) - Number(sizeAfter.value)).toFixed(2)).toString() || '失败'
    return result
})

// const beforeRead = (file: any) => {
//     console.log(file);
// }

const afterRead = (file: any) => {
    // 此时可以自行将文件上传至服务器
    console.log(file);
    sizeBefore.value = ((file.file.size / 1024).toFixed(2)).toString()
    typeBefore.value = file.file.type

    // 创建一个新的 Image 对象来获取图片尺寸
    const img = new Image();
    img.src = URL.createObjectURL(file.file);
    img.onload = function() {
        // 图片加载完成后，获取其尺寸
        console.log('图片宽度:', img.width, '高度:', img.height);
        sizeBeforeWidth.value = img.width?.toString()
        sizeBeforeHeight.value = img.height?.toString()
    };
};

const onturn = () => {
    console.log(fileList.value[0]);
    handleClick()
    if (fileList.value.length < 1) {
        showToast('请选择图片')
        return;
    } else {
        showConfirmDialog({
            title: '',
            confirmButtonColor: '#bca1f3',
            message: '确定要开始压缩吗？',
        })
        .then(() => {
            // recognize 第一个参数：图像，第二个：语种
            // const url = 'https://tesseract.projectnaptha.com/img/eng_bw.png'
            settings.handlerLoadingShow(true)
            // const _imgFile = fileList.value[0]?.content
            const _imgFile = fileList.value[0]?.file

            // 创建一个新的 Image 对象来获取图片尺寸
            const img = new Image();
            img.src = URL.createObjectURL(_imgFile);
            img.onload = function() {
                // 图片加载完成后，获取其尺寸
                console.log('图片宽度:', img.width, '高度:', img.height);
                sizeAfterWidth.value = img.width?.toString()
                sizeAfterHeight.value = img.height?.toString()
            };

            useCompressor(_imgFile).then((_imgFile: any) => {
                const formData = new FormData()
                formData.append('file', _imgFile)
                formData.append('type', 'freight')
                console.log('_imgFile', _imgFile)
                sizeAfter.value = ((_imgFile.size / 1024).toFixed(2)).toString()
                typeAfter.value = _imgFile.type
                getBase64(_imgFile).then((res: any) => {
                    const img_url = res.split(',')[1]
                    compressorAfter.value = `data:image/png;base64,${img_url}`
                    settings.handlerLoadingShow(false)
                    console.log('compressorAfter.value', compressorAfter.value)
                })
            })
        })
        .catch(() => {
            // on cancel
        });
    }
}

const download = () => {
    const img = new Image();
    img.crossOrigin = 'Anonymous'; // 允许跨域
    img.src = compressorAfter.value

    img.onload = async () => {
        const canvas = document.createElement('canvas');
        const ctx = canvas.getContext('2d');
        canvas.width = img.width;
        canvas.height = img.height;
        ctx?.drawImage(img, 0, 0);

        canvas.toBlob(blob => {
            const url = URL.createObjectURL(blob as any);
            const link = document.createElement('a');
            link.href = url;
            link.download = 'image.png'; // 设置下载的文件名
            link.click();

            // 释放URL对象
            URL.revokeObjectURL(url);
        }, typeAfter.value);
    }
}

const clean = () => {
    handleClick()
    fileList.value = []
    compressorAfter.value = ''
}

onMounted(() => {

})

</script>


<style lang="scss" scoped>
.compressImgContent {
    width: 100%;
    position: relative;
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 15px;
    .compressImgBefore {
        display: flex;
        flex-direction: column;
        align-items: center;
        .imgInfo {
            p {
                margin-bottom: 5px;
                color: #666;
            }
        }
    }
    .compressImgBtn {
        width: 100%;
        margin-top: 15px;
        .active {
            // background-color: blue; /* 改变背景颜色 */
            transform: scale(1.1); /* 放大按钮 */
        }
    }
    .compressImgAfter {
        margin-top: 20px;
        display: flex;
        flex-direction: column;
        align-items: center;
        .compressImgAfterImg {
            width: 100%;
            height: auto;
            display: flex;
            flex-direction: column;
            align-items: center;
            margin-bottom: 5px;
            img {
                width: 100%;
                height: 100%;
                object-fit: cover;
            }
        }
        .imgInfo {
            p {
                margin-bottom: 5px;
                color: #666;
            }
        }
    }
    .compressImgResult {
        width: 100%;
        margin-top: 15px;
        text-align: center;
        p {
            margin-top: 5px;
            color: #15256a;
        }
    }
    .compressImgBtn {
        width: 100%;
        margin-top: 20px;
    }
}
</style>
